package com.ssm.plus.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ssm.plus.entity.Article;
import com.ssm.plus.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    IArticleService articleService;

    @GetMapping("/")
    public List<Article> list(@RequestParam(required = false, defaultValue = "") String title) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(title)) {
            wrapper.eq("title", title);
        }
        return articleService.list(wrapper);
    }

    @GetMapping("/find")
    public Article find(@RequestParam String code) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        return articleService.getOne(wrapper, false);
    }

    @GetMapping("/page")
    public Page<Article> page(@RequestParam(required = false, defaultValue = "1") Integer number,
                              @RequestParam(required = false, defaultValue = "") String orderById,
                              @RequestParam(required = false, defaultValue = "") String userId,
                              @RequestParam(required = false, defaultValue = "") String title,
                              @RequestParam(required = false, defaultValue = "") String tag) {
        Page<Article> page = new Page<>(number, 10);
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (!StringUtils.isEmpty(title)) {
            wrapper.eq("title", title);
        }
        if (!StringUtils.isEmpty(tag)) {
            wrapper.like("tag", String.format("%%%s%%", tag));
        }
        if (!StringUtils.isEmpty(orderById)) {
            wrapper.orderByDesc("id");
        }
        return articleService.page(page, wrapper);
    }

    @PostMapping("/")
    public Object save(@RequestBody Article article) {
        return articleService.saveOrUpdate(article);
    }

    @GetMapping("/{id}")
    public Object get(@PathVariable Long id) {
        return articleService.getById(id);
    }

    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Long id) {
        return articleService.removeById(id);
    }
}
